package cn.java79.quiz.web;

import cn.java79.quiz.entity.Practise;
import cn.java79.quiz.entity.Questions;
import cn.java79.quiz.entity.User;
import cn.java79.quiz.pojo.AjaxResult;
import cn.java79.quiz.pojo.Section;
import cn.java79.quiz.service.*;
import cn.java79.quiz.util.StrUtil;
import com.alibaba.fastjson.JSON;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Properties;
import java.util.Random;

@WebServlet("*.stu")
public class StudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String path = req.getServletPath();
        path = path.substring(1, path.length() - 4);
        try {
            Method m = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
            m.invoke(this, resp, req);
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(501, "服务器出现了错误" + e);
        }
    }

    //登录操作
    public void login(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String name = req.getParameter("login");
        String pass = req.getParameter("pass");
        String code = req.getParameter("code");
        String genCode = (String) req.getSession().getAttribute("piccode");
        String ar[] = genCode.split(" ");
        //规定时间不能超过30秒
        if (System.currentTimeMillis() - Long.parseLong(ar[1]) >= 20 * 1000) {
            req.setAttribute("msg", "验证码已经失效，请刷新后再试！");
            req.getRequestDispatcher("studentlogin.jsp").forward(req, resp);
            return;
        }
        if (code == null || !code.equals(ar[0])) {
            req.setAttribute("msg", "验证码输入错误！");
            req.getRequestDispatcher("studentlogin.jsp").forward(req, resp);
            return;
        }

        //登录成功之后，信息放入cookie
        User login = UserService.ME.login(name, pass);
        if (login != null) {
            ///
            Cookie c = new Cookie("loginname", name);
            c.setMaxAge(86400 * 7);
            Cookie c2 = new Cookie("loginpass", pass);
            c2.setMaxAge(86400 * 7);
            resp.addCookie(c);
            resp.addCookie(c2);
            ///
            req.getSession().setAttribute("STUDENT_LOGIN", login);
            resp.sendRedirect("studentmain.jsp");
            return;
        }
        //
        req.setAttribute("msg", "错误的用户名或者密码");
        req.getRequestDispatcher("studentlogin.jsp").forward(req, resp);
    }

    //显示知识点
    public void showSection(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        List<Section> top = SectionService.ME.findTop();
        req.setAttribute("sections", top);

        req.getRequestDispatcher("/WEB-INF/jsps/sectionSelect.jsp").forward(req, resp);
    }

    public void showSection2(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        List<Section> top = SectionService.ME.findTop();
        req.setAttribute("sections", top);
        String type = req.getParameter("type");

        req.getRequestDispatcher("/WEB-INF/jsps/sectionSelect2.jsp").forward(req, resp);


    }

    //根据知识点随机获得一道题
    public void selectQues(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        long skillid = StrUtil.toLong(req.getParameter("secid"));

        long[] ar = new long[0];
        String[] testids = req.getParameterValues("v");//已经做过的题目
        if (testids != null) {
            //转换成long数组
            ar = new long[testids.length];
            for (int i = 0; i < ar.length; i++) {
                ar[i] = StrUtil.toLong(testids[i]);
            }
        }
        //已经做过的数组怎么获得？

        Questions questions = QuestionsService.ME.randomSel(skillid, ar);
        if (questions == null) {
            req.setAttribute("msg", "已经没有了！");
            req.getRequestDispatcher("/WEB-INF/jsps/quizOver.jsp").forward(req, resp);
            return;
        }

        req.setAttribute("q", questions);
        req.getRequestDispatcher("/WEB-INF/jsps/quiz.jsp").forward(req, resp);
        return;


    }


    public void resetemail(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String email = req.getParameter("youremail");
        boolean b = UserService.ME.checkMail(email);
        if (!b) {
            req.setAttribute("msg", "这个电子邮件没有注册过！");
            req.getRequestDispatcher("/resetpassEmail.jsp").forward(req, resp);
            return;
        }

        //发送邮件。。。
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            sb.append(ch[r.nextInt(len)]);
        }
        try {
            //
            req.getSession().setAttribute("toresetemail", email);
            req.getSession().setAttribute("resetcode", String.valueOf(sb));
            req.getSession().setAttribute("resettime", System.currentTimeMillis());
            send(email, sb.toString());
        } catch (MessagingException e) {
            req.setAttribute("msg", "邮件发送失败，请核对地址");
            req.getRequestDispatcher("/send.jsp").forward(req, resp);
            e.printStackTrace();
            return;
        }
        req.setAttribute("msg", "邮件发送成功");
        req.getRequestDispatcher("/sendEmailSucess.jsp").forward(req, resp);
    }

    //重置密码
    public void resetPasswordByEmail(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String inputcode = req.getParameter("code");
        String newpass = req.getParameter("newpass");
        String newpassRepeat = req.getParameter("newpassrepeat");
        try {
            //获得之前session中存储的值
            String mail = (String) req.getSession().getAttribute("toresetemail");
            String code = (String) req.getSession().getAttribute("resetcode");
            long sendTime = (Long) req.getSession().getAttribute("resettime");

            if (!newpass.equals(newpassRepeat)) {
                req.setAttribute("msg", "两次密码输入不一致！");
                req.getRequestDispatcher("/sendEmailSucess.jsp").forward(req, resp);
                return;
            }
            if (System.currentTimeMillis() - sendTime > 60 * 1000) {
                //验证码一分钟有效
                req.setAttribute("msg", "时间太久,请重新发送");
                req.getRequestDispatcher("/resetpassEmail.jsp").forward(req, resp);
                return;
            }
            if (!code.equals(inputcode)) {
                req.setAttribute("msg", "验证码输入错误！");
                req.getRequestDispatcher("/resetpassEmail.jsp").forward(req, resp);
                return;
            }
            //验证通过，重置密码
            UserService.ME.resetPass(mail, newpass);
            req.setAttribute("msg", "密码重置成功！");
            req.getRequestDispatcher("/studentlogin.jsp").forward(req, resp);
        } finally {
            //清除上次发送的验证码
            req.getSession().removeAttribute("toresetemail");
            req.getSession().removeAttribute("resetcode");
            req.getSession().removeAttribute("resettime");
        }
    }

    public void send(String to, String code) throws MessagingException, UnsupportedEncodingException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        // properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        //properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        MimeMessage message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress("19328954@qq.com", "测试标题", "UTF-8"));
        // 设置收件人邮箱地址
        //message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com")});
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//一个收件人
        // 设置邮件标题
        message.setSubject("测试发送邮件");
        // 设置邮件内容
        //message.setText("邮件内容邮件内容邮件内容xmqtest<a href='#'>你好</a>");
        //message.setText("邮件内容邮件内容邮件内容xmqtest<a href='https://localhost:9996/quiz/resetpass.ques?email="+to+"' target='_blank'>你好</a>","gbk","html");
        message.setText("您重置密码的验证符是<h1 style='font-size:40px;color:red;'>" + code + "</h1>", "gbk", "html");
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户,也就是管理员的邮箱
        transport.connect("19328954@qq.com", "bduvgniictqbibh");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();


    }

    //检查是否重复，email,phone,loginnane
    public void checkrepeat(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String type = req.getParameter("type");
        String value = req.getParameter("v");
        //value=value.substring(30);
        boolean b = UserService.ME.checkRepeat(type, value);
//        try {
//            Thread.sleep(4500);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //输出结果
        resp.getWriter().print(b);
    }

    //随机产生一个测试。。。
    public void generateQuiz(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        Long secid = StrUtil.toLong(req.getParameter("secid"));
        //当前登录的用户
        User user = (User) req.getSession().getAttribute("STUDENT_LOGIN");
        long quizid = QuizService.ME.generateQuiz(user.getId(), user.getLoginname(), secid);

        resp.sendRedirect("showquiz.stu?quizid=" + quizid);
    }

    public void showquiz(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        Long quizid = StrUtil.toLong(req.getParameter("quizid"));
        List<Questions> quizs = QuizService.ME.getQuizs(quizid);
        req.setAttribute("quizid", quizid);
        req.setAttribute("questions", quizs);
        req.setAttribute("times", quizs.size() * 60);//一题一分钟，暂定
        req.getRequestDispatcher("/WEB-INF/jsps/quiz2.jsp").forward(req, resp);
    }

    public void savePractise(HttpServletResponse response, HttpServletRequest req) throws ServletException, IOException {
        Long qid = StrUtil.toLong(req.getParameter("qid"));
        boolean result = Boolean.parseBoolean(req.getParameter("result"));
        long user = ((User) req.getSession().getAttribute("STUDENT_LOGIN")).getId();
        Practise p = new Practise();
        p.setQid(qid);
        p.setUid(user);
        p.setResult(result);
        int add = PractiseService.ME.add(p);
        AjaxResult result1 = add > 0 ? AjaxResult.success() : AjaxResult.error();
        response.setContentType("application/json;charset=utf-8");
        //发送给前端
        response.getWriter().print(JSON.toJSONString(result1));
    }

    public void savequiz(HttpServletResponse response, HttpServletRequest req) throws ServletException, IOException {
        String answer = req.getParameter("youanswer");
        System.out.println(answer + "?>>>");
        //转换json字符串到对象集合
        List<Practise> practise = JSON.parseArray(answer, Practise.class);
        PractiseService.ME.addS(practise);
        //会有事务丢失的情况
        //        for(Practise p:practise){
        ////           PractiseService.ME.add(p);
        ////        }


        AjaxResult result1 = AjaxResult.success();
        response.setContentType("application/json;charset=utf-8");
        //发送给前端
        response.getWriter().print(JSON.toJSONString(result1));
    }
    //扣积分
    public void kofen(HttpServletResponse response, HttpServletRequest req) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("STUDENT_LOGIN");
        long id = user.getId();
        boolean kofen = UserService.ME.kofen(id, 5);
        AjaxResult result1 = kofen ? AjaxResult.success() : AjaxResult.error("扣分失败！");
        response.setContentType("application/json;charset=utf-8");
        //发送给前端
        response.getWriter().print(JSON.toJSONString(result1));
    }
    //看答案，扣积分
    public void showAnser(HttpServletResponse response, HttpServletRequest req) throws ServletException, IOException {
        long id = ( (User) req.getSession().getAttribute("STUDENT_LOGIN")).getId();
        long qid=StrUtil.toLong(req.getParameter("qid"));
        //

        Questions questions = UserService.ME.showQuizAnswer(id,qid);;
        AjaxResult result = AjaxResult.rtn(questions);
        response.setContentType("application/json;charset=utf-8");
        //发送给前端
        response.getWriter().print(JSON.toJSONString(result));
    }
}